require 'rubygems'
require 'stomp'
require 'rexml/document'

module Heterotopia
  class Client
    # Construct a new client.
    def initialize(options = {})
      host_options = {:login    => '',
                      :passcode => '',
                      :host     => 'localhost',
                      :port     => 61613,
                      :ssl      => false}.merge(options)
      options = {:hosts => [host_options], :connect_headers => {
        'transformation' => 'jms-map-xml'
      }}
      @client = Stomp::Client.new(options)
    end

    def do_command(&block)
      @client.subscribe("/queue/commands", {'transformation' => 'jms-map-xml'}) do |msg|
        doc = REXML::Document.new(msg.body)
        data = {}
        doc.elements.each("map/entry") do |element|
          key = element.elements[1].text
          value = element.elements[2].text
          data[key] = value
        end
        yield(data) if block_given?
      end
    end
    
    def to_xml(data)
      doc = REXML::Document.new("<map />")
      data.each do |key,value|
        entry_element = doc.root.add_element "entry"
        key_element = entry_element.add_element "string"
        key_element.text = key.to_s
        value_element = entry_element.add_element "string"
        value_element.text = value.to_s
      end
      doc.to_s
    end

    def set_player(session_id, obj)
      @client.publish("/queue/sessions", to_xml({"sessionId" => session_id, "playerObject" => obj}), {
        :suppress_content_length => true,
        'transformation' => 'jms-map-xml'})
    end

    def send_text(session_id, text)
      @client.publish("/queue/sessions", to_xml({"sessionId" => session_id, "text" => text}), {
        :suppress_content_length => true,
        'transformation' => 'jms-map-xml'})
    end

    def boot_player(session_id)
      @client.publish("/queue/sessions", to_xml({"sessionId" => session_id, "sessionLifecycle" => "close"}), {
        :suppress_content_length => true,
        'transformation' => 'jms-map-xml'})
    end

    def join
      @client.join
    end
  end
end
